<?php
use app\common\lib\task\Task;

class Http{
	private $host = "0.0.0.0";
	private $port = 8811;

	public $http = null;
	public function __construct(){
		$this->http = new swoole_http_server($this->host,$this->port);
		$this->http->set(
			[
				'enable_static_handler' => true,
				'document_root'=>'/home/www/swoole/thinkphp/public/static',
				'worker_num' => 2,
				'task_worker_num' => 2
			]
		);
		$this->http->on("workerStart", [$this,'onWorkerStart']);
		$this->http->on("request", [$this,'request']);
		$this->http->on("task", [$this,'onTask']);
		$this->http->on("finish", [$this,'onFinish']);
		//$this->http->on("close", [$this,'onClose']);
	}

	public function httpStart(){
		$this->http->start();
	}

	public function onTask($serv, $task_id, $workerId, $data){
		$task = new Task();
		$method = $data['method'] ?? 'sendSms';
		$msg = $task->$method($data['data']);
		return $msg;
	}

	public function onFinish($serv, $task_id, $data){
		echo "taskid:{$task_id},data:".json_encode($data);
	}

	public function onWorkerStart(swoole_server $server, $worker_id){
		//定义应用目录
		define('APP_PATH', __DIR__ . '/../application/');
		// 加载基础文件
		require __DIR__ . '/../thinkphp/start.php';
	}

	public function request($request, $response){
		$_SERVER = [w];
		if(isset($request->header)){
			foreach($request->header as $k => $v){
				$_SERVER[strtoupper($k)] = $v;
			}
		}
		$_GET = [];
		if(isset($request->get)){
			foreach($request->get as $k => $v){
				$_GET[strtolower($k)] = $v;
			}
		}
		$_POST = [];
		$_POST['http_server'] = $this->http;
		if(isset($request->post)){
			foreach($request->post as $k => $v){
				$_POST[strtolower($k)] = $v;
			}
		}

		ob_start();
		try{
			think\Container::get('app', [defined('APP_PATH') ? APP_PATH : ''])
			->run()
			->send();
		}catch(\Exception $e){
			echo  $e->getMessage();
		}

		$res = ob_get_contents();
		ob_end_clean();
		$response->end($res);
	//$http->close();
	}


}

$http = new Http();
$http->httpStart();

//topthink/think-swoole